//
//  MZHUD.swift
//  MZTool_Example
//
//  Created by gby on 2023/1/29.
//  Copyright © 2023 CocoaPods. All rights reserved.
//

import Foundation
import SVProgressHUD
import MBProgressHUD
import MZTool


private let customdismisstimeInterval:TimeInterval = 1.5
private let customdMinSize:CGSize = CGSize.init(width: 130, height: 44)
private let fontSize:UIFont = UIFont.systemFont(ofSize: 14)
private let cornerRadius:CGFloat = 6


public class MZHUD: NSObject {
    @objc public static func config(_ setting: (()-> Void)?){
        SVProgressHUD.setMinimumSize(customdMinSize)
        SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark)
        SVProgressHUD.setMinimumDismissTimeInterval(customdismisstimeInterval)
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.clear)
        SVProgressHUD.setFont(fontSize)
        SVProgressHUD.setBackgroundColor(UIColor.black)
        SVProgressHUD.setForegroundColor(UIColor.white)
        SVProgressHUD.setCornerRadius(cornerRadius)
        
        setting?()
    }
    
    //MARK:---------------------SVProgressHUD
    @objc public static func show() -> Void {
        SVProgressHUD.show()
    }
    
    @objc public static func show(withStatus str: String?) -> Void {
        SVProgressHUD.show(withStatus: str ?? "")
    }
    
    @objc public static func show(info str: String?) -> Void {
        SVProgressHUD.showInfo(withStatus: str ?? "")
    }
    
    @objc public static func showProgress(progress pro:Float){
        SVProgressHUD.showProgress(pro)
    }
    
    @objc public static func showProgress(progress pro:Float, withStatus str:String?){
        (str == nil) ? SVProgressHUD.showProgress(pro) : SVProgressHUD.showProgress(pro, status: str ?? "")
    }
    
    @objc public static func showSuccess(withStatus str: String?){
        SVProgressHUD.showSuccess(withStatus: str ?? "")
    }
    
    @objc public static func showError(withStatus str: String?){
        SVProgressHUD.showError(withStatus: str ?? "")
    }
    
    @objc public static func dissmiss(){
        SVProgressHUD.dismiss()
    }
    
    //MARK:---------------------MBProgressHUD
    @objc public static func show(to: UIView?) -> Void {
        hudShowFor(for: to, withStatus: "",custommode:.indeterminate)
    }
    
    @objc public static func show(to: UIView?, offect: CGPoint) -> Void {
        hudShowFor(for: to, withoffect: offect, withStatus: "",custommode:.indeterminate)
    }
    
    @objc public static func show(to: UIView?, withStatus str: String?) -> Void {
        hudShowFor(for: to, withStatus: str ?? "",custommode:.indeterminate)
    }
    
    @objc public static func show(to: UIView?, info str: String?) -> Void {
        hudShowFor(for: to, withStatus: str ?? "",custommode:.text)
    }
    
    @objc public static func show(to: UIView?, info str: String?, delay:TimeInterval) -> Void {
        hudShowFor(for: to, withStatus: str ?? "",custommode:.text , delay: delay)
    }
    
    @objc public static func show(to: UIView?, info str: String?, offect: CGPoint) -> Void {
        hudShowFor(for: to, withoffect: offect, withStatus: str ?? "",custommode:.text)
    }
    
    @objc public static func show(to: UIView?, info str: String?, offect: CGPoint, delay:TimeInterval) -> Void {
        hudShowFor(for: to, withoffect: offect, withStatus: str ?? "",custommode:.text, delay: delay)
    }
    
    @objc public static func show(to: UIView?, info str: String?, offect: CGPoint , ani:Bool) -> Void {
        hudShowFor(for: to, withoffect: offect, animation:ani , withStatus: str ?? "",custommode:.text)
    }
    
    @objc public static func showProgress(to: UIView?, progress pro:Float) -> Void {
        hudShowFor(for: to, withStatus: "",custommode:.determinate)
    }
    
    @objc public static func showProgress(to: UIView?, progress pro:Float, withStatus str:String?) -> Void {
        hudShowFor(for: to, withStatus: str ?? "",custommode:.determinate)
    }
    
    @objc public static func dissmiss(to: UIView?){
        dissmiss(for: to, immediately: false, afterDelay: 0.35)
    }
    
    @objc public static func dissmiss(to: UIView?, immediately: Bool){
        dissmiss(for: to, immediately: true, afterDelay: 0.35)
    }
    
    @objc public static func dissmiss(to: UIView?, afterDelay: CGFloat){
        dissmiss(for: to, immediately: false, afterDelay: afterDelay)
    }
    
    static private func dissmiss(for to: UIView?,immediately: Bool, afterDelay: CGFloat){
        guard to != nil else {
            return
        }
        for (_, hud) in to!.subviews.enumerated().reversed(){
            if hud is MBProgressHUD {
                if immediately {
                    DispatchQueue.global(qos: .unspecified).async {
                        DispatchQueue.main.async {
                            (hud as! MBProgressHUD).hide(animated: false)
                        }
                    }
                }else{
                    DispatchQueue.global(qos: .unspecified).async {
                        DispatchQueue.main.async {
                            (hud as! MBProgressHUD).hide(animated: true, afterDelay: TimeInterval(afterDelay))
                        }
                    }
                }
                break
            }
        }
    }
    

    static private func hudShowFor(for to: UIView?,
                                   withoffect offect: CGPoint = CGPoint.init(x: 0, y: 0),
                                   animation ani: Bool = false,
                                   withStatus str: String ,
                                   custommode:MBProgressHUDMode,
                                   delay:TimeInterval? = customdismisstimeInterval,
                                   defView window:UIView? = ({
        var keywindow : UIWindow?
        if #available(iOS 13, *) {
            keywindow = UIApplication.shared.windows.first { $0.isKeyWindow }
        } else {
            keywindow = UIApplication.shared.keyWindow
        }
        return keywindow
    })() ) -> Void {
        self.dissmiss(to: to, immediately: true)
        
        let hud = MBProgressHUD.showAdded(to: to ?? window!, animated: true)
        hud.label.text = str
        hud.label.numberOfLines = 0
        hud.label.font = fontSize
        hud.label.textColor = .white
        hud.mode = custommode
        hud.minSize = customdMinSize
        hud.bezelView.backgroundColor = UIColor.black
        let oneview = hud.bezelView.subviews.first
        if let effectview = oneview as? UIVisualEffectView {
            effectview.contentView.backgroundColor = UIColor.black
        }
        hud.bezelView.layer.cornerRadius = cornerRadius
        hud.contentColor = UIColor.white
        hud.offset = offect
        
        switch custommode {
        case .indeterminate:
            if let img = MZ.IMG("icon_default_loading") {
                hud.minSize = CGSize(width: customdMinSize.height * 2, height: customdMinSize.height)
                hud.mode = .customView
                
                let loadingview = MZHUDLoagingView.init(frame: CGRect(x: 0, y: 0, width: 40, height: 40), img: img)
                
                hud.customView = loadingview
            }
        case .text:
            hud.margin = 6
            
            defer {
                DispatchQueue.global(qos: .unspecified).async {
                    DispatchQueue.main.async {
                        hud.hide(animated: true, afterDelay: delay ?? 0.35)
                    }
                }
            }
            
            guard #available(iOS 11, *), ani else{
                return
            }
//            let popstringani = POPSpringAnimation.init(propertyNamed: kPOPLayerScaleXY)
//            popstringani?.fromValue = NSValue.init(cgPoint: CGPoint.init(x: 0.5, y: 0.5))
//            popstringani?.toValue = NSValue.init(cgPoint: CGPoint.init(x: 1, y: 1))
//            popstringani?.springBounciness = 20;
//            popstringani?.completionBlock = {[weak hud] (animation: POPAnimation?,isok: Bool) in
//                let suoxiao = POPBasicAnimation.init(propertyNamed: kPOPViewScaleXY)
//                suoxiao?.fromValue = NSValue.init(cgPoint: CGPoint.init(x: 1, y: 1))
//                suoxiao?.toValue = NSValue.init(cgPoint: CGPoint.init(x: 0.8, y: 0.8))
//                suoxiao?.completionBlock = { (animation: POPAnimation?,isok: Bool) in
//                    let dismiss = POPBasicAnimation.init(propertyNamed: kPOPViewScaleXY)
//                    dismiss?.fromValue = NSValue.init(cgPoint: CGPoint.init(x: 0.8, y: 0.8))
//                    dismiss?.toValue = NSValue.init(cgPoint: CGPoint.init(x: 0, y: 0))
//                    dismiss?.beginTime = CACurrentMediaTime() + 1
//                    dismiss?.completionBlock = { (animation: POPAnimation?,isok: Bool) in
//                        hud?.hide(animated: false, afterDelay: customdismisstimeInterval)
//                    }
//                    hud?.pop_add(dismiss, forKey: "dismiss")
//                }
//                hud?.pop_add(suoxiao, forKey: "suoxiao")
//            }
//            hud.layer.pop_add(popstringani, forKey: "hudpop")
        default:
            return
        }
        
    }
}


class MZHUDLoagingView: UIImageView {
    deinit {
        
    }
    
    required convenience init(frame: CGRect, img: UIImage?) {
        self.init()
        
        self.frame = frame
        self.image = img
        
        let animation = CABasicAnimation.init(keyPath: "transform")
        animation.fromValue = NSValue.init(caTransform3D: CATransform3DIdentity)
        animation.toValue = NSValue.init(caTransform3D: CATransform3DMakeRotation(CGFloat(Double.pi/2), 0.0, 0.0, 1.0))
        animation.duration = 0.3
        animation.isCumulative = true
        animation.repeatCount = MAXFLOAT
        animation.isRemovedOnCompletion = false
        self.layer.add(animation, forKey: "animationimgv")
        
    }
}
